<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/6/24
 * Time: 20:05
 */

namespace app\common\service\lastWeek;

use think\Db;
use think\facade\Config;
use app\common\service\CommonService;
use app\common\service\lastWeek\LastWeekControlAnalysisService;

/**
 * 上周小结-策略分析
 * Class LastWeekStrategyAnalysisService
 * @package app\common\service\lastWeek
 */
class LastWeekStrategyAnalysisService
{

    public function getAirQualityCompare($param = [])
    {
        $pollutant_name = str_replace('.', '', strtolower($param['pollutant_name']));
        // 历史同期
        $commonService      = new CommonService();
        $history_start_time = $commonService->getHistoryTime($param['start_time']);
        $history_end_time   = $commonService->getHistoryTime($param['end_time']);
        $historyData        = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                        from air_quality_station_aqi_realtime_day
                        where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $history_start_time, $history_end_time]);

        // 同等气象条件历史数据平均值
        $history_period = $this->getHistoryPeriodData($param);

        // 实际值
        $realData = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                    from air_quality_station_aqi_realtime_day
                                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        // 日期补全处理
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $history                        = $lastWeekControlAnalysisService->getAllData(['start_time' => $history_start_time, 'end_time' => $history_end_time], $historyData, $pollutant_name);
        $real                           = $lastWeekControlAnalysisService->getAllData($param, $realData, $pollutant_name);
        // 比较闰年多出来的天  以平年的天数的为准
        if (count($real['date']) < count($history['date'])) {
            $cha = array_diff($history['date'], $real['date']);//出现在第一个数组中但其他输入数组中没有的值
            foreach ($history['date'] as $k => $v) {
                if ($v == $cha[0]) {
                    unset($history['data'][0][$k]);
                }
            }
        } elseif (count($history['date']) < count($real['date'])) {
            $cha = array_diff($real['date'], $history['date']);//出现在第一个数组中但其他输入数组中没有的值
            foreach ($real['date'] as $k => $v) {
                if ($v == $cha[0]) {
                    unset($real['data'][0][$k]);
                    unset($history_period['data'][0][$k]);
                }
            }
        }
        if (count($history_period) == 0) {
            for ($i = 0; $i < count($real['date']); $i++) {
                $history_period['date'][$i]    = $real['date'][$i];
                $history_period['data'][0][$i] = '-';
            }
        }
        // 管控目标
        $control = [];
        for ($i = 0; $i < count($real['date']); $i++) {
            $control['date'][$i]    = $real['date'][$i];
            $control['data'][0][$i] = '-';
        }
        $result = [
            'date' => $real['date'],
            'data' => [$history['data'][0], $history_period['data'][0], $real['data'][0], $control['data'][0]],
        ];
        return $result;
    }

    /**
     * 同等气象条件历史数据平均值
     * @author yy by 2019/7/2
     * @param array $param
     * @return array
     */
    public function getHistoryPeriodData($param = [])
    {
        // 查看历史日期中静稳指数一样的日期
        $static        = Db::query("select stable_weather_index_value as static_index, DATE_FORMAT(publish_time, '%Y-%m-%d') as date 
                                  from stable_weather_index_realtime_day_new 
                                  where station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') <= ? and publish_time = predict_time", [$param['station_id'], $param['end_time']]);
        $static_date   = array_column($static, 'date');
        $commonService = new CommonService();
        // 上周七天的日期
        $date_last_week = $commonService->getDate($param['start_time'], $param['end_time']);
        foreach ($date_last_week as $k => $v) {
            !in_array($v, $static_date) ? $static[] = ['date' => $v, 'static_index' => '-'] : '';
        }
        $new_static = array_column($static, null, 'date');
        // 日期补全处理
        $last_week = [];
        foreach ($date_last_week as $k => $v) {
            $last_week[$v] = isset($new_static[$v]['static_index']) ? $new_static[$v]['static_index'] : '-'; // 可能缺少日期
        }
        $same = [];
        // 查看历史中相同指数的日期
        foreach ($last_week as $k2 => $v2) {
            foreach ($new_static as $k3 => $v3) {
                if (strtotime($k3) < strtotime($k2) && $v3['static_index'] == $v2) {
                    $same[$k2][] = $k3; //与当天静稳指数相同的日期的集合
                }
            }
        }
        // 查看所有污染物的值
        $pollutant_name = str_replace('.', '', $param['pollutant_name']);
        $real           = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                    from air_quality_station_aqi_realtime_day
                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') <= ?",
            [$param['region_id'], $param['station_id'], $param['end_time']]);
        $real_data      = array_column($real, null, 'date');
        $list           = [];
        foreach ($same as $k3 => &$v3) {
            $v3        = array_flip($v3); // 一维数组键值互换
            $list[$k3] = array_intersect_key($real_data, $v3); // 比较并获取第一个数组中与其他数组键相同的值
        }
        foreach ($list as $k4 => &$v4) {
            $v4 = count($v4) > 0 ? array_sum(array_column($v4, $pollutant_name)) / count($v4) : '-';
        }
        $result_init = [];
        foreach ($list as $k5 => $v5) {
            $result_init[] = ['date' => $k5, $pollutant_name => $v5];
        }
        //  日期补全
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $result                         = $lastWeekControlAnalysisService->getAllData($param, $result_init, $pollutant_name);
        return $result;
    }

    /**
     * aqi空气质量趋势图
     * @author yy by 2019/6/24
     * @param array $param
     * @return mixed
     */
    public function getAqiTrend($param = [])
    {
        # 减排前预报值
        $before_data = Db::query("select aqi, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                        from air_quality_station_aqi_forecast_day
                        where region_id = ? and station_id = ? and is_integer = 1 and publish_time = predict_time and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        # 实测
        $real_data = Db::query("select aqi, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                    from air_quality_station_aqi_realtime_day
                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        # 日期补全处理
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $before_data                    = $lastWeekControlAnalysisService->getAllData($param, $before_data, 'aqi');
        $real_data                      = $lastWeekControlAnalysisService->getAllData($param, $real_data, 'aqi');
        # 减排后预报值 = 减排前预报值-预案值 TODO
        $after_data = [];
        for ($i = 0; $i < count($before_data['date']); $i++) {
            $after_data['date'][$i]    = $before_data['date'][$i];
            $after_data['data'][0][$i] = '-';
        }
        $result = [
            'date' => $before_data['date'],
            'data' => [$before_data['data'][0], $after_data['data'][0], $real_data['data'][0]]
        ];
        return $result;
    }

}